import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In, Between } from 'typeorm';
import { DeviceRequestLogEntity } from '../entity/request-log';
import { StudentStudentEntity } from '../../student/entity/student';
import { AppointmentInfoEntity } from '../../appointment/entity/info';
import { DeviceDeviceCheckEntity } from '../entity/deviceCheck';

// 假设 RequestParams 类型定义如下，如果已有定义请忽略
interface RequestParams { 
  birthdate: string;
  comment: string;
  duration: number;
  equipment: string;
  gender: string;
  klass: string;
  measurementTime: string;
  name: string;
  number: string;
  odAL: number;
  odALCR: number;
  odALSrc: string;
  odAST: string;
  odK1: string;
  odK2: string;
  odPD: number;
  odSD: string;
  odWTW: number;
  osAL: number;
  osALCR: number;
  osALSrc: string;
  osAST: string;
  osK1: string;
  osK2: string;
  osPD: number;
  osSD: string;
  osWTW: number;
  password: string;
  phoneNumber: string;
  username: string;
  sysStudentId: number;
}

// 假设 Log 类型定义如下，如果已有定义请忽略
interface Log { 
  requestParams: RequestParams;
}
/**
 * 设备请求日志
 */
@Provide()
export class DeviceRequestLogService extends BaseService {
  @InjectEntityModel(DeviceRequestLogEntity)
  deviceRequestLogEntity: Repository<DeviceRequestLogEntity>;

  @InjectEntityModel(StudentStudentEntity)
  studentStudentEntity: Repository<StudentStudentEntity>;

  @InjectEntityModel(AppointmentInfoEntity)
  appointmentInfoEntity: Repository<AppointmentInfoEntity>;

  @InjectEntityModel(DeviceDeviceCheckEntity)
  deviceDeviceCheckEntity: Repository<DeviceDeviceCheckEntity>;

  /**
   * 添加请求日志
   * @param method 请求方法
   * @param params 请求参数
   */
  async addLog(method: string, params: any) {
    let methodType = ['GET', 'POST', 'PUT', 'DELETE'];
    const savedEntity = await this.deviceRequestLogEntity.save({
      deviceId: 1,
      statusCode: 200,
      requestMethod: methodType.indexOf(method),
      requestParams: typeof params === 'string' ? params : JSON.stringify(params),
      processTime: 1000,
      createTime: new Date(),
      updateTime: new Date(),
      requestTime: new Date(),
    });
    if (params) {
      try {
        let requestData: RequestParams = typeof params === 'string' ? JSON.parse(params) : params;
        // 转换 gender 字段
        const genderMap: { [key: string]: number } = {
          'M': 1, // 假设 M 对应 1
          'F': 2  // 假设 F 对应 2
        };
        const transformedData = {
          ...requestData,
          gender: genderMap[requestData.gender] || 0 // 如果没有匹配到，默认设为 0
        };

        // 根据电话查询学生信息
        const phoneNumber = transformedData.phoneNumber;
        if (phoneNumber) {
          const student = await this.studentStudentEntity.findOne({ where: { phone: phoneNumber } });
          if (student) {
            transformedData.sysStudentId = student.id;
          }
        }
  
        await this.deviceDeviceCheckEntity.save(transformedData);

        if (phoneNumber) {
          // 查询 studentId
          const student = await this.studentStudentEntity.findOne({ where: { phone: phoneNumber } });
          if (student) {
            const studentId = student.id;
            // 获取当天日期
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);

            // 查询当天的预约
            const appointment = await this.appointmentInfoEntity.findOne({
              where: {
                studentId: studentId,
                appointmentStatus: 0,
                appointmentTime: Between(today, tomorrow)
              }
            });

            if (appointment) {
              // 更新预约状态
              appointment.appointmentStatus = 1;
              await this.appointmentInfoEntity.save(appointment);
              console.log('当天预约状态已更新为 1');
            }
          }
        }
      } catch (error) {
        console.error('保存 requestParams 到 deviceDeviceCheckEntity 时出错:', error);
      }
    }
    console.log('数据保存成功:', savedEntity);
    return savedEntity;
  }

  // 重构后的 getLogPhone 方法
  async getLogPhone(): Promise<{ logs: { [key: string]: any }[]; updatedPhoneStudentIdList: { phone: string; studentId: number | null, sign: string | null }[] }> { 
    try { 
      // 获取日志数据
      const logs: DeviceRequestLogEntity[] = await this.deviceRequestLogEntity.find(); 

      // 提取电话号码
      const phoneNumbersFromLogs = logs.map((log) => { 
        try { 
          const requestParams: RequestParams = JSON.parse(log.requestParams); 
          return requestParams.phoneNumber; 
        } catch (parseError) { 
          // console.error('解析 requestParams 时出错:', parseError); 
          return ''; 
        } 
      }).filter((phone) => phone !== '');

      // 批量查询学员信息
      const students = await this.studentStudentEntity.find({ where: { phone: In(phoneNumbersFromLogs) } });
      const studentIds = students.map((student) => student.id);
      const appointments = await this.appointmentInfoEntity.find({ where: { studentId: In(studentIds), appointmentStatus: 1 } });
      const appointmentStudentIds = appointments.map((appointment) => appointment.studentId);


      // 创建一个电话到学员 ID 的映射
      const phoneToStudentIdMap = new Map<string, number | null>();
      phoneNumbersFromLogs.forEach((phone) => { 
        phoneToStudentIdMap.set(phone, null); 
      });
      students.forEach((student) => { 
        phoneToStudentIdMap.set(student.phone, student.id); 
      });
      // 生成最终的数组
      const phoneStudentIdList = Array.from(phoneToStudentIdMap.entries()).map(([phone, studentId]) => ({ 
        phone, 
        studentId,
        sign: null
      }));

      let updatedPhoneStudentIdList = phoneStudentIdList.map(item => { 
        // 签到拼接
        if (item.studentId !== null && appointmentStudentIds.includes(item.studentId)) { 
          return { 
            ...item, 
            sign: '签到' 
          }; 
        } else if (item.studentId!== null && !appointmentStudentIds.includes(item.studentId)) { 
          return { 
            ...item, 
            sign: '未签到' 
          }; 
        } else {
          return {
            ...item,
            sign: '未注册'
          }
        }
      });

      // 清洗 logs 数据，拼接 studentId 和 sign
      const cleanedLogs: { [key: string]: any }[] = logs.map((log) => { 
        try { 
          const requestParams: RequestParams = JSON.parse(log.requestParams); 
          const phone = requestParams.phoneNumber; 
          const name = requestParams.name;
          const equipment = requestParams.equipment;
          const studentId = phoneToStudentIdMap.get(phone); 
          const value = updatedPhoneStudentIdList.find(item => item.phone === phone); 
          const sign = value? value.sign : '未注册'; 
          // 直接返回对象，而非 DeviceRequestLogEntity 实例
          return { 
            ...log,
            equipment, 
            phone,
            name,
            studentId, 
            sign 
          }; 
        } catch (parseError) { 
          // console.error('解析 requestParams 时出错:', parseError); 
          return { 
            ...log, 
            studentId: null, 
            sign: '未注册' 
          }; 
        } 
      });
      console.log('cleanedLogs', cleanedLogs);
      return {
        logs: cleanedLogs, 
        updatedPhoneStudentIdList 
      };
    } catch (error) { 
      // 处理错误
      console.error('获取日志电话号码时出错:', error); 
      return {
        logs: [],
        updatedPhoneStudentIdList: [] 
      }; 
    } 
  }
}
